package com.study.csv;
import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
/**
 * <p>添加类描述</p>
 *
 * @author chentao
 * @version v 0.1 2024/6/17 17:08
 */
public class Csv5 {
    public static void main(String[] args) throws IOException {
        String v1 = "name1:v1";
        String v2 = "name2:v2";
        v2=null;
        String v3 = "name3:v3";
        File file = new File("C:\\test\\test100.csv");
        FileOutputStream out = new FileOutputStream(file);

        // 判断是否存在 v1 和 v2
        boolean hasV1 = v1 != null && !v1.isEmpty();
        boolean hasV2 = v2 != null && !v2.isEmpty();
        boolean hasV3 = v3 != null && !v3.isEmpty();
        // 调整表头
        StringBuilder header = new StringBuilder("\t姓名,\t年级");
        if (hasV1) {
            header.append(",\t").append(v1.split(":")[1]);
        }
        if (hasV2) {
            header.append(",\t").append(v2.split(":")[1]);
        }
        if (hasV3) {
            header.append(",\t").append(v3.split(":")[1]);
        }
        header.append("\r\n");

        // 写入表头到文件
        out.write(header.toString().getBytes("GBK"));

        // 数据行的模式
        StringBuilder rowPattern = new StringBuilder("\t{0},\t{1}");
        int colIndex = rowPattern.toString().split(",").length; // 从2开始，因为{0}和{1}已经被占用
        if (hasV1) {
            rowPattern.append(",\t{").append(colIndex).append("}");
            colIndex++;
        }
        if (hasV2) {
            rowPattern.append(",\t{").append(colIndex).append("}");
            colIndex++;
        }
        if (hasV3) {
            rowPattern.append(",\t{").append(colIndex).append("}");
            colIndex++;
        }
        rowPattern.append("\r\n");

        // 准备数据行
        ArrayList<Person> peoples = new ArrayList<>();
        Person person = new Person();
        person.setName("1");
        person.setAge("1");
        person.setName1("setName1");
        person.setName2("setName2");
        person.setName3("setName3");
        peoples.add(person);

        for (Person people : peoples) {
            ArrayList<Object> rowData = new ArrayList<>();
            rowData.add(people.getName());
            rowData.add(people.getAge());
            if (hasV1) {
                rowData.add(people.getName1());
            }
            if (hasV2) {
                rowData.add(people.getName2());
            }
            if (hasV3) {
                rowData.add(people.getName3());
            }
            System.out.println("1223123"+ MessageFormat.format(rowPattern.toString(), rowData.toArray()));
            out.write(MessageFormat.format(rowPattern.toString(), rowData.toArray()).getBytes("GBK"));
        }

        out.close();
    }
}